<template>
  <div class="edit-info-dialog">
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="switchMaskShow"
      :append-to-body="false"
      center
      class="small-common-dialog-size">
      <div>
        <Title title="修改信息" font-size="16px" style="margin-bottom: 24px;" />
        <div class="edit-list-box">
          <el-form v-if="currentKeyword !== 'priceTime'" :model="editInfo" :label-width="currentKeyword === 'baseInfo' ? '70px' : currentKeyword === 'currencyPriceInfo' ? '95px' : '90px'" :class="(currentKeyword === 'baseInfo') || 'price-style'" label-position="right" size="small">
            <template v-for="(key, i) in commonData" >
              <el-form-item
                v-if="key.key !== 'id' &&
                  key.key !== 'tags' &&
                  key.key !== 'babyBirthday' &&
                  key.key !== 'taxPoint' &&
                  key.key !== 'actualTaxPoint' &&
                  key.key !== 'babPrice' &&
                  key.key !== 'babySex'
                "
                :key="i"
                :label="key.label"
                class="input-style"
              >
                <el-input
                  :id="`${key.key}`"
                  v-model="editInfo[key.key]"
                  :type="key.inputType"
                  :maxlength="key.maxlength || 'auto'"
                  @keyup.native="limitSize(editInfo, key.key ,key.maxNumlength,key.miniNum)" />
              </el-form-item>
              <!-- <el-form-item
                v-if="key.key === 'accountName' ||
                  key.key === 'fansNum' ||
                  key.key === 'address'
                "
                :key="i"
                :label="key.label"
                class="input-style"
              >
                <el-input
                  :id="`${key.key}`"
                  v-model="editInfo[key.key]"
                  :type="key.inputType"
                  :maxlength="key.maxlength || 'auto'"
                  :disabled="key.key === 'accountName'"
                  @keyup.native="limitSize(editInfo, key.key ,key.maxNumlength)" />
              </el-form-item> -->
              <!-- 两个税点：用来单独控制是否可以输入 -->
              <el-form-item
                v-if="key.key === 'taxPoint' || key.key === 'actualTaxPoint'"
                :key="i"
                :label="key.label"
                :maxlength="key.maxlength || 'auto'"
                class="input-style"
                @keyup.native="limitSize(editInfo, key.key ,key.maxNumlength,key.miniNum)"
              >
                <el-input v-model="editInfo[key.key]" :type="key.inputType" :disabled="editInfo['payMethod'] === '云支付'" />
              </el-form-item>
            </template>
          </el-form>
          <!-- 有效价格时间区间 key === priceTime -->
          <div v-if="currentKeyword === 'priceTime'" class="price-time-item">
            <div class="label">有效价格时间区间</div>
            <el-date-picker
              v-model="priceTimeRange"
              :editable="false"
              class="price-time-range"
              type="daterange"
              value-format="timestamp"
              size="small"
              format="yyyy/MM/dd"
              start-placeholder="开始日期"
              end-placeholder="结束日期"/>
          </div>
        </div>
      </div>

      <div class="edit-btn-container" style="display:flex;justify-content:center;">
        <el-button size="small" class="btn ok-btn-style" type="primary" @click.stop="handelOk">确定</el-button>
        <el-button size="small" class="btn cancel-btn-style" type="default" plain @click.stop="switchMaskShow">取消</el-button>
      </div>
    </el-dialog>
    <!-- <MaskContainer
      ref="MaskContainer"
      :main-style="{
        width: currentKeyword === 'priceTime' ? '360px' : '340px',
        maxHeight: '420px',
        minHeight: '320px'
      }"
      title="修改信息"
      @handelOk="handelOk">

    </MaskContainer> -->
  </div>

</template>
<script>
import MaskContainer from './MaskContainer';
import Title from '@/components/Title';
import { ExportExcelData } from '@/views/medium/mixin/mediumData';
// API
import { editInfoApi } from '@/api/medium';
// filters
import { parseTime } from '@/utils/index';
import { priceFormat, thousandFormat } from '@/filters/number';
export default {
  components: { MaskContainer, Title },
  props: {
    activeTabsId: {
      type: String,
      default: ''
    },
    // 平台 tab
    tabs: {
      type: Array,
      default: null
    }
  },
  data() {
    return {
      dialogVisible: false,
      ExportExcelData,
      editInfoList: {},
      editInfo: {},
      commonData: [],
      currentKeyword: '',
      priceTimeRange: [],
      itemPlateformId: ''
    };
  },
  computed: {
    isAll() {
      return this.activeTabsId === '';
    },
    activeTabs() {
      if (this.isAll) {
        return this.itemPlateformId.toString();
      }
      return this.activeTabsId;
    }
  },
  methods: {
    limitSize(item, key, maxlength, miniNum = 4) {
      if (item[key] && item[key] !== '' && maxlength) {
        if (item[key].indexOf('.') >= 0) {
          const before = item[key].split('.')[0];
          const after = item[key].split('.')[1];
          if (before.length > maxlength || after.length > 1) {
            item[key] = `${before.substr(0, maxlength)}.${after.substr(0, miniNum)}`;
          }
        }
        if (item[key].indexOf('.') < 0 && item[key].length > maxlength) {
          item[key] = item[key].substr(0, maxlength);
        }
      }
    },
    initData() {
      this.commonData = {};
      this.priceTimeRange = [];
    },
    tabMaskShow(item, key) {
      this.itemPlateformId = item.platformId;
      this.currentKeyword = key;
      this.handleData(key);
      this.switchMaskShow();
      this.editInfoList = _.cloneDeep(item);
      this.editInfo = this.editInfoList[key];
      if (this.editInfo.fansNum) {
        // this.editInfo.fansNum = Number(this.editInfo.fansNum / 10000).toFixed(1);// 处理旧数据，都只保留1位小数
        this.editInfo.fansNum = `${Number(this.editInfo.fansNum) * 10000}`;
      }
      this.handleUnit(this.editInfo);
      if (key === 'priceTime') {
        const startTime = parseTime(this.editInfo['startTime']) || '';
        const endTime = parseTime(this.editInfo['endTime']) || '';
        this.priceTimeRange = [startTime, endTime];
      }
    },
    async handelOk() {
      const paramsClone = _.cloneDeep(this.editInfo);
      this.handleUnit(paramsClone, true);
      const params = {
        ...paramsClone,
        mediumId: this.editInfoList.mediumId
      };
      // 如果修改票面信息时，支付方式输入的是‘云支付’，怎么两个税点都置空
      if (this.currentKeyword === 'invoiceInfo' && params.payMethod === '云支付') {
        params.taxPoint = '';
        params.actualTaxPoint = '';
      }
      delete params.tags;
      // 如果修改票面信息时，支付方式输入的是‘云支付’，怎么两个税点都置空
      if (this.currentKeyword === 'dataInfo') {
        params.exposure = params.exposure ? parseInt(params.exposure) : params.exposure;
        params.averageReadNum = params.averageReadNum ? parseInt(params.averageReadNum) : params.averageReadNum;
        params.averageInteractionNum = params.averageInteractionNum ? parseInt(params.averageInteractionNum) : params.averageInteractionNum;
      }
      // 有效价格区间
      if (this.currentKeyword === 'priceTime') {
        const startTime = this.priceTimeRange ? this.priceTimeRange[0] : '';
        const endTime = this.priceTimeRange ? this.priceTimeRange[1] : '';
        params.startTime = startTime;
        params.endTime = endTime;
      }
      if (this.currentKeyword === 'dataInfo') {
        params.averageLikeNum = params.averageLikeNum | params.averageLikeNum === 0 ? Number(params.averageLikeNum) * 1000 : null;
        params.averagePlayNum = params.averagePlayNum | params.averagePlayNum === 0 ? Number(params.averagePlayNum) * 1000 : null;
      }
      if (this.currentKeyword === 'contactInfo' && (!params.internalContact || params.internalContact === '')) {
        this.$message({
          type: 'warning',
          message: '请填写内部联系人'
        });
        return false;
      }
      const result = await editInfoApi(params, this.currentKeyword);
      if (result.code === 200) {
        this.$message({
          type: 'success',
          message: '修改成功'
        });
        this.$emit('editInfoFun', { params, currentKeyword: this.currentKeyword });
        this.switchMaskShow();
      } else {
        this.$message({
          type: 'error',
          message: result.message
        });
      }
    },
    // 处理单位: isOpposite是否反向编译
    handleUnit(editInfo, isOpposite = false) {
      const key = this.currentKeyword;

      if (editInfo['babyBirthday'] && editInfo['babyBirthday'].length === 4) {
        editInfo['babyBirthday'] = editInfo['babyBirthday'] + '0101';
      }
      if (key === 'priceInfo') {
        for (const price in editInfo) {
          if (!isOpposite && Number(editInfo[price])) {
            editInfo[price] = priceFormat(editInfo[price], 2);
          } else if (isOpposite && Number(editInfo[price])) {
            editInfo[price] = Math.round(Number(editInfo[price]) * 100);
          }
        }
      } else if (key === 'currencyPriceInfo') {
        const currencyPriceInfo = ['discount'];
        for (const price in editInfo) {
          if (!isOpposite && !currencyPriceInfo.includes(price) && Number(editInfo[price])) {
            editInfo[price] = priceFormat(editInfo[price], 2);
          } else if (isOpposite && !currencyPriceInfo.includes(price) && Number(editInfo[price])) {
            editInfo[price] = Math.round(Number(editInfo[price]) * 100);
          }
        }
      } else {
        // 单位是万的字段
        const unitThousand = ['fansNum', 'averagePlayNum', 'averageOnlinePlay'];
        // 判断是否小红书，小红书的阅读量单位还是个不是万
        if (Number(this.activeTabs) !== 3) {
          unitThousand.push('averageReadNum');
        }
        // 判断是否抖音
        if (Number(this.activeTabs) === 4) {
          unitThousand.push('averageInteractionNum');
        }
        // 判断是否短视频或直播
        if (Number(this.activeTabs) === 5 || Number(this.activeTabs) === 6) {
          unitThousand.push('averageLikeNum');
        }
        unitThousand.forEach(item => {
          if (!isOpposite && editInfo[item]) {
            editInfo[item] = editInfo[item] && editInfo[item] !== ''
              ? thousandFormat(editInfo[item], false, false)
              : editInfo[item];
          } else {
            editInfo[item] = editInfo[item] && editInfo[item] !== ''
              ? Number(editInfo[item])
              : editInfo[item];
          }
        });
        if (!isOpposite) {
          editInfo['babPrice'] = priceFormat(editInfo['babPrice'], 2);
        } else {
          editInfo['babPrice'] = editInfo['babPrice'] !== null && editInfo['babPrice'] !== '' ? Math.round(Number(editInfo['babPrice']) * 100) : '';
        }
      }
    },
    // 处理字段数据
    handleData(keyword) {
      const exportExcelDataClone = _.cloneDeep(this.ExportExcelData);
      const commonData = exportExcelDataClone.common;
      let platform = '';
      for (let i = 0; i < this.tabs.length; i++) {
        const item = this.tabs[i];
        if (item.key === this.activeTabs) {
          platform = item.ziduan;
          break;
        } else {
          // 更多类型
          platform = 'duanshipin';
        }
      }
      const platformData = this.ExportExcelData[platform];
      // 结合
      for (let j = 0; j < commonData.length; j++) {
        const commonItem = commonData[j];
        for (let f = 0; f < platformData.length; f++) {
          const platformItem = platformData[f];
          if (commonItem._keyword === platformItem._keyword) {
            commonItem.child = commonItem.child.concat(platformItem.child);
          }
        }
      }
      let keywordArr = [];
      commonData.forEach(item => {
        if (item._keyword === keyword) {
          keywordArr = item.child;
        }
      });
      this.commonData = keywordArr;
    },
    switchMaskShow() {
      this.dialogVisible = !this.dialogVisible;
    }
  }
};
</script>
<style scoped lang="scss">
.edit-list-box {
  // height: 325px;
  // padding-bottom: 10px;
  margin-bottom: 32px;
}
.edit-info-dialog {
  &::v-deep {
    .el-dialog__body {
      padding-top: 10px;
      .edit-btn-container {
        .btn {
          height: 32px;
          border-radius: 4px;
        }
        .ok-btn-style {
          width: 120px;
        }
      }
    }
  }
}
.price-time-item {
  margin-top: 20px;
  display: flex;
  align-items: center;
  .label {
    margin-right: 10px;
    color: #666;
    font-size: 14px;
  }
  & ::v-deep {
    .el-range-editor--small {
      &.el-input__inner {
        height: 30px;
        width: 225px;
        &:hover {
          border-color: #406EFF;
        }
      }
      .el-range-input {
        font-size: 13px;
      }
      .el-range__close-icon {
        width: 14px;
      }
      .el-range-separator{
        line-height: 22px;
        padding: 0;
        box-sizing: content-box;
      }
    }
  }
}
</style>
<style lang="scss">
.edit-list-box {
  .el-scrollbar__bar.is-horizontal {
    display: none;
  }
  .tags-input-container {
    .el-form-item__content {
      width: 240px;
    }
    .el-row--flex {
      flex-wrap: wrap;
    }
  }
  .price-style {
    .el-form-item__label {
      line-height: 17px !important;
    }
  }
  .el-form-item {
    margin-bottom: 24px !important;
    overflow: hidden;
    &:last-child {
      margin-bottom: 0 !important;
    }
  }
  .el-form-item__label {
    // width: 100% !important;
    height: 32px;
    // display: flex;
    // align-items: center;
    color: #666;
    font-size: 14px !important;
  }
  .date-input {
    .el-date-editor {
      width: 240px;
    }
  }
  .input-style {
    .el-input {
      width: 240px;
      &.is-disabled {
        .el-input__inner {
          width: 240px;
          height: 32px;
          border-radius: 4px;
          background-color: #f5f7fa;
          border-color: #E4E7ED;
          color: #515151;
          cursor: not-allowed;
        }
      }
    }
  }
}
</style>
